<script setup>
import { onMounted, ref } from 'vue'
import { User, Lock, Monitor } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'
import { usePageColorStore } from '@/stores'
import { userLoginService } from '@/api/user'
import { ZlMessage } from '@/utils/message'
import loginLeftDarkImg from '@/assets/login-left-dark.png'
import loginLeftLightImg from '@/assets/login-left-light.png'
import { verifyCodeGetSingleService } from '@/api/verify-code'
import { baseURL } from '@/utils/request'

const router = useRouter()
const userStore = useUserStore()
const pageColorStore = usePageColorStore()

// 表单相关
const loginFormRef = ref()
const loginForm = ref({
  username: '',
  password: '',
  captcha: '',
  captchaId: '',
  imgPath: ''
})
// 整个表单校验规则
const rules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

const getCode = async () => {
  const res = await verifyCodeGetSingleService()
  loginForm.value.id = res.data.data.id
  loginForm.value.imgPath = res.data.data.imgPath
  loginForm.value.captchaId = res.data.data.id
}
getCode()

const login = async () => {
  await loginFormRef.value.validate()
  const res = await userLoginService(loginForm.value)
  if (res.data.code === 200) {
    userStore.setToken(res.data.data.token)
    if (
      res.data.data.user.userImg != null &&
      res.data.data.user.userImg != ''
    ) {
      res.data.data.user.userImg = baseURL + res.data.data.user.userImg
    }
    userStore.setUserInfo(res.data.data.user)
    ZlMessage.success(res.data.msg)
    const urlParams = new URLSearchParams(window.location.search)
    const nameValue = urlParams.get('name')
    if (nameValue == null) {
      router.push('/')
    } else {
      router.push('/' + nameValue)
    }
  } else if (res.data.code === 201) {
    getCode()
  }
}

onMounted(() => {
  const windowHeight = window.innerHeight
  document.querySelector('.login-page').style.marginTop =
    (windowHeight - 500) / 2 + 'px'

  // 获取要淡入的元素
  const elementRight = document.querySelector('.right')
  const elementLeft = document.querySelector('.left')

  // 使用setTimeout来延迟设置透明度为1，以触发过渡效果
  setTimeout(function () {
    elementRight.style.opacity = '1'
    elementRight.style.transform = 'translate(0, 0)'
  }, 100) // 延迟100毫秒触发透明度改变，从而触发淡入效果
  setTimeout(function () {
    elementLeft.style.opacity = '1'
    elementLeft.style.transform = 'translate(0, 0)'
  }, 900)
})

// 重新获取验证码
const refreshCaptcha = () => {
  getCode()
}

// 跳转至注册页面
const reg = () => {
  router.push('/reg')
}
</script>

<template>
  <el-row
    class="login-page"
    :class="{
      loginDark: pageColorStore.isDark,
      loginLight: !pageColorStore.isDark
    }"
  >
    <el-col
      :span="12"
      class="left"
      style="display: flex; align-items: center; justify-content: center"
    >
      <img
        :src="pageColorStore.isDark ? loginLeftDarkImg : loginLeftLightImg"
        alt=""
        width="50%"
      />
    </el-col>
    <el-col :span="12" class="right">
      <div class="logo-box">
        <zlcode-h2>Login —— Page</zlcode-h2>
      </div>
      <div style="padding-top: 20px; padding-bottom: 20px; text-align: center">
        <el-text size="small">
          To
          <el-text
            size="small"
            type="primary"
            style="cursor: pointer"
            @click="reg"
            >register</el-text
          >
          an account, please contact - qq: 623847465
        </el-text>
      </div>
      <el-form
        @keydown.enter="login()"
        :model="loginForm"
        ref="loginFormRef"
        label-width="auto"
        label-position="left"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            :prefix-icon="User"
            placeholder="username"
            size="large"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            :prefix-icon="Lock"
            size="large"
            placeholder="password"
            v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input
            v-model="loginForm.captcha"
            style="width: 71%"
            size="large"
            :prefix-icon="Monitor"
            placeholder="code"
            prop="captcha"
          >
          </el-input>
          <!-- 假设验证码图片是一个img标签，实际中可能是动态生成的 -->
          <a-image
            :show-loader="true"
            :preview="false"
            :src="loginForm.imgPath"
            alt="验证码"
            :style="{
              'margin-left': '5%',
              cursor: 'pointer',
              width: '24%',
              'border-radius': '5px'
            }"
            @click="refreshCaptcha"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%; height: 45px; font-size: 18px"
            @click="login"
            >登录</el-button
          >
        </el-form-item>
        <el-text
          tag="p"
          size="small"
          type="info"
          style="text-align: right; cursor: pointer"
          @click="router.push('/resetpwd')"
          >找回密码</el-text
        >
      </el-form>
    </el-col>
  </el-row>
</template>
<style lang="scss" scoped>
.loginDark {
  background-image: lin/ear-gradient(to right, #434343 0%, black 100%);
}
.loginLight {
  background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  // border: 2px solid #b3b1b1;
}
.login-page {
  width: 1000px;
  height: 500px;
  margin: 0 auto;
  overflow: hidden;
  border-radius: 20px;
  // box-shadow: 0 0 38px 10px rgba(0, 0, 0, 0.1);
  .left {
    // background: url('@/assets/login-left.png') no-repeat center / cover;
    opacity: 0;
    transform: translate(-250px, 0);
    /* transition: all 1s; */
    transition:
      transform 1s,
      opacity 2s;
    overflow: hidden;
  }
  .right {
    padding: 20px;
    transform: translate(0, -60px);
    opacity: 0;
    /* 初始透明度为0 */
    transition:
      transform 1s,
      opacity 2s;
    .logo-box {
      padding-top: 50px;
      display: flex;
      justify-content: center;
      img {
        width: 90%;
      }
    }
  }

  /*搜索input框 */
  :deep(.el-input__wrapper) {
    border-radius: 15px;
  }

  :deep(.el-button) {
    border-radius: 15px;
    border: none;
  }

  :deep(.arco-image-img) {
    margin-left: 5%;
    cursor: pointer;
    width: 93%;
    border-radius: 10px;
  }
}
</style>
